export type LoadingChangeBack = (loading: boolean) => void

export class LoadingUtils {
  private _loading = false;
  private count = 0;
  private loadingChangeBack: LoadingChangeBack | undefined

  get loading(): boolean {
    return this._loading;
  }

  /**
   * 不允许设置，只允许使用show和close
   * @param value
   */
  set loading(value: boolean) {
    console.error('不允许设置，只允许使用show和close')
  }

  public setLoadingChangeBack(value: LoadingChangeBack) {
    this.loadingChangeBack = value;
  }

  constructor(loadingChangeBack?: LoadingChangeBack) {
    if (loadingChangeBack) {
      this.loadingChangeBack = loadingChangeBack
    }
  }


  public show() {
    this.count++;
    if (this.count > 0) {
      if (!this._loading && this.loadingChangeBack) {
        this.loadingChangeBack(true)
      }
      this._loading = true
    }
  }

  public close() {
    this.count--;
    if (this.count <= 0) {
      if (this._loading && this.loadingChangeBack) {
        this.loadingChangeBack(false)
      }
      this._loading = false
      this.count = 0
    }
  }

  /**
   * 自动loading，简化写法 <br/>
   * loadingUtils.autoLoading(updateUser(this.form))<br/>
   * :loading="loadingUtils.loading"
   * @param promise
   */
  public autoLoading<T extends Promise<unknown>>(promise: T): T {
    this.show()
    const result = new Promise<unknown>((resolve, reject) => {
      promise
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
          .finally(() => {
            this.close()
          })
    })
    return result as T
  }
}
